<?php

namespace App\Api\Controllers;

use App\Models\Goods;
use App\Models\WebConfig;
use Dingo\Api\Http\Request;
use Dingo\Api\Routing\Helpers;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;

class GoodsController extends Controller
{
    use Helpers;
    //搜索结果
    public function goodsSearch(Request $request)
    {
        $keywords=$request->input('keywords');
        if(!$keywords){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'需要填写关键字'
            ]);
        }
        //SELECT * FROM goods WHERE ;

        $data=Goods::whereRaw("MATCH (title,author) AGAINST ('{$keywords}' IN NATURAL LANGUAGE MODE)")->get();
        if(count($data)>0){
            $extra_discount=WebConfig::where('name','extra_discount')->value('value')?:0;
            foreach ($data as $v){
                $v->discount +=$extra_discount;
                $v->goods_status=$this->checkGoodsStatus($v->id);
            }
            return $this->response->array([
                'status_code'=>200,
                'message'=>'已查询到相关书籍',
                'result'=>$data
            ]);
        }else{
            return $this->response->array([
                'status_code'=>201,
                'message'=>'未找到相关书籍'
            ]);
        }

    }
    //商品详情
    public function goodsDetail($id)
    {
        $data=Goods::find($id);
        if($data){
            $data->goods_status=$this->checkGoodsStatus($id);
            $extra_discount=WebConfig::where('name','extra_discount')->value('value')?:0;//附加折扣
            $data->discount +=$extra_discount;
            return $this->response->array([
                'status_code'=>200,
                'message'=>'获取数据成功',
                'result'=>$data
            ]);
        }else{
            return $this->response->array([
                'status_code'=>201,
                'message'=>'未找到相关书籍'
            ]);
        }

    }

    //检查书籍在当前用户学校是否有人在售
    public function checkGoodsStatus($goodsId)
    {
        $user=$this->auth->user();
        $res=DB::table('depot')
            ->where([['university_id',$user->university_id],['campus_id',$user->campus_id],['goods_id',$goodsId],['user_id','!=',$user->id],['goods_status',1]])
            ->whereColumn('total','>','lock_num')
            ->first();
        return $res?1:0;
    }



}